﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.datatables;
using l1cs.server.model.Instance;
using l1cs.server;
using l1cs.server.utils;
using l1cs.server.clientpackets;
using l1cs.server.templates;
using l1cs.server.model;
using l1cs.server.server.utils;
using MySql.Data.MySqlClient;
using System.Data;
using l1cs.server.model.map;
using System.Diagnostics;
using l1cs.server.model.npc.action;

namespace l1cs
{
#if DEBUG
    class TestClass
    {
        private static Logger _log = Logger.getLogger( typeof( TestClass ).FullName );

        String accountName = "dummy";
        String password = "dummy";
        String ip = "127.0.0.1";
        String host = "localhost";
        int char_id;
        String char_name = "テスト用";


        public TestClass()
        {
            GomiClear();

            L1PcInstance pc = new L1PcInstance();
            Account account = initAccount();
            initPcInstance( pc );

            benshWorldMap();

            testAccounts( account );
            testCharacterTable( pc );
            testItemTable();
            testCharacterItemTable( pc );

            //testReadDatabase( pc );

            testXml( pc );
        }

        private void testXml( L1PcInstance pc )
        {
            L1Object l1object = null;
            NpcActionTable.getInstance().get( "test", pc, l1object );
        }

        /// <summary>
        /// DB関係を呼び出しテストする
        /// </summary>
        /// <param name="pc"></param>
        private void testReadDatabase( L1PcInstance pc )
        { /*TTOK*/
            ArmorSetTable.getInstance();
            {//AuctionBoardTable
                AuctionBoardTable auctionBoardTable = new AuctionBoardTable();　// スレッド停止してるから
                int houseid = 900000;
                L1AuctionBoard auctionBoard = auctionBoardTable.getAuctionBoardTable( houseid );
                if ( auctionBoard == null )
                    auctionBoard = new L1AuctionBoard();
                else
                    auctionBoardTable.deleteAuctionBoard( houseid );
                auctionBoard.setHouseId( houseid );
                auctionBoard.setHouseName( "テストハウス" );
                auctionBoard.setHouseArea( 111 );
                auctionBoard.setDeadline( DateTime.Now );
                auctionBoard.setPrice( 1000 );
                auctionBoard.setLocation( "ロケーション" );
                auctionBoard.setOldOwner( "前の家主" );
                auctionBoard.setOldOwnerId( 123 );
                auctionBoard.setBidder( "血盟名" );
                auctionBoard.setBidderId( 456 );
                auctionBoardTable.insertAuctionBoard( auctionBoard );

                auctionBoard.setHouseId( houseid );
                auctionBoard.setHouseName( "テストハウスUPDATE" );
                auctionBoard.setHouseArea( 222 );
                auctionBoard.setDeadline( DateTime.Now.AddYears( 20 ) );
                auctionBoard.setPrice( 2222 );
                auctionBoard.setLocation( "ロケーションUPDATE" );
                auctionBoard.setOldOwner( "前の家主UPDATE" );
                auctionBoard.setOldOwnerId( 9999 );
                auctionBoard.setBidder( "血盟名UPDATE" );
                auctionBoard.setBidderId( 888 );
                auctionBoardTable.updateAuctionBoard( auctionBoard );

                auctionBoardTable.deleteAuctionBoard( houseid );
            }
            {//L1Board
                L1Board board = new L1Board();
                DateTime date = DateTime.Today;
                String title = "タイトル";
                String content = "内容";
                for ( int i = 0; i < 100; i++ )
                {
                    board.date = date.ToString( "yyyy/MM/dd" );
                    board.title = title + " " + i;
                    board.content = content + " " + i;
                    BoardTable.getInstance().writeTopic( pc, board );
                    date = date.AddDays( 1 );
                }
                L1Board[] boards = BoardTable.getInstance().getViewList( 0 );
                boards = BoardTable.getInstance().getViewList( 1 );
                // 削除
                String sqlstr = "Delete FROM board";
                using ( MySqlWrapper wrapper = new MySqlWrapper() )
                {
                    MySqlCommand cmd = new MySqlCommand( sqlstr );
                    wrapper.ExecNonQuery( cmd );
                }
                for ( int i = 0; i < 5; i++ )
                {
                    board.date = date.ToString( "yyyy/MM/dd" );
                    board.title = title + " " + i;
                    board.content = content + " " + i;
                    BoardTable.getInstance().writeTopic( pc, board );
                    date = date.AddDays( 1 );
                }
                boards = BoardTable.getInstance().getViewList( 0 );
                //1件だけ検索
                board = BoardTable.getInstance().getBoard( 0 );
                //ありえないIDで検索
                board = BoardTable.getInstance().getBoard( 10000 );
                //削除メソッドで削除
                BoardTable.getInstance().deleteTopic( 0 );
                BoardTable.getInstance().deleteTopic( 1 );
                BoardTable.getInstance().deleteTopic( 2 );
                BoardTable.getInstance().deleteTopic( 3 );
                BoardTable.getInstance().deleteTopic( 4 );
            }
            {//BuddyTable
                int[,] testBuddy = new int[,] {
                    {10, 10},
                    {11, 10},
                    {12, 10},
                    {13, 10},
                    {14, 10},
                    {15, 10},
                    {16, 10},
                    {18, 10},
                    {19, 10},
                    {20, 11},
                    {21, 11},
                    {22, 11},
                    {23, 11},
                };
                using ( MySqlWrapper wp = new MySqlWrapper() )
                {
                    String sqlstr = @"INSERT INTO character_buddys SET 
                                        char_id    = ?1, 
                                        buddy_id   = ?2, 
                                        buddy_name = ?3";
                    using ( MySqlWrapper wrapper = new MySqlWrapper() )
                    {
                        for ( int i = 0; i <= testBuddy.GetUpperBound( 0 ); i++ )
                        {
                            try
                            {
                                MySqlCommand cmd = new MySqlCommand( sqlstr );
                                cmd.Parameters.Add( "?1", MySqlDbType.Int32 ).Value = testBuddy[i, 0];
                                cmd.Parameters.Add( "?2", MySqlDbType.Int32 ).Value = testBuddy[i, 1];
                                cmd.Parameters.Add( "?3", MySqlDbType.String ).Value = testBuddy[i, 1] + "血盟";
                                wrapper.ExecNonQuery( cmd );
                            }
                            catch ( Exception ) { }
                        }
                    }
                    BuddyTable.getInstance();
                }
            }
            {//CastleTable
                List<L1Castle> castles = new List<L1Castle>();
                foreach ( L1Castle castle in CastleTable.getInstance().getCastleTableList() )
                {
                    L1Castle castle2 = CastleTable.getInstance().getCastleTable( castle.getId() );
                    castle2.setWarTime( castle2.getWarTime().AddDays( 7 ) );
                    castles.Add( castle2 );
                }
                foreach ( L1Castle castle in castles )
                {
                    CastleTable.getInstance().updateCastle( castle );
                }
            }
            {//CharacterConfigTable
                int id = 1000;
                int length = 2000;
                byte[] data = Encoding.UTF8.GetBytes( "abcdefg" );
                CharacterConfigTable.getInstance().storeCharacterConfig( id, length, data );
                data = Encoding.UTF8.GetBytes( "1234567" );
                CharacterConfigTable.getInstance().updateCharacterConfig( id, length, data );
                int count = CharacterConfigTable.getInstance().countCharacterConfig( id );
                CharacterConfigTable.getInstance().deleteCharacterConfig( id );
            }
            {//CharBuffTable
                // タイマーが働かないとうまくテストできないのでブレイクポイントを
                // いれて値を変更すること。
                CharBuffTable.SaveBuff( pc );
                CharBuffTable.DeleteBuff( pc );
            }
            {//ChatLogTable
                // チャットログはデフォルトOFFになっているので
                // ブレイクポイントをいれて値を変更すること。
                ChatLogTable.getInstance().storeChat( pc, pc, "チャット", 0 );
                ChatLogTable.getInstance().storeChat( pc, null, "チャット", 0 );
            }
            {//ClanTable
                String baseName = pc.getName();
                int[] lid = new int[] { 3, 9, 18, 36, 51, 76, 100 };
                L1Clan[] clans = new L1Clan[lid.Length];
                int cid = 0;
                clans[cid] = ClanTable.getInstance().createClan( pc, "クラン" + cid );
                if ( clans[cid] == null )
                {
                    ClanTable.getInstance().deleteClan( "クラン" + cid );
                    clans[cid] = ClanTable.getInstance().createClan( pc, "クラン" + cid );
                }
                // 血盟倉庫に適当にアイテムを入れる
                int id = ItemTable.getInstance().findItemIdByName( "ボーン アーマー" );
                L1ItemInstance item = ItemTable.getInstance().createItem( id );
                clans[cid].getDwarfForClanInventory().insertItem( item );
                //clans[cid].getDwarfForClanInventory().deleteAllItems();
                id = ItemTable.getInstance().findItemIdByName( "ボーン ヘルム" );
                item = ItemTable.getInstance().createItem( id );
                clans[cid].getDwarfForClanInventory().insertItem( item );
                item.setCount( 2 );
                clans[cid].getDwarfForClanInventory().updateItem( item );
                id = ItemTable.getInstance().findItemIdByName( "パンプキンヘルム" );
                item = ItemTable.getInstance().createItem( id );
                clans[cid].getDwarfForClanInventory().insertItem( item );
                clans[cid].getDwarfForClanInventory().deleteItem( item );

                for ( int i = 0; i < 100; i++ )
                {
                    pc.setName( baseName + i );
                    pc.setId( IdFactory.getInstance().nextId() );
                    if ( i == lid[cid] )
                    {
                        cid++;
                        clans[cid] = ClanTable.getInstance().createClan( pc, "クラン" + cid );
                        if ( clans[cid] == null )
                        {
                            ClanTable.getInstance().deleteClan( "クラン" + cid );
                            clans[cid] = ClanTable.getInstance().createClan( pc, "クラン" + cid );
                        }
                    }
                    pc.setClanid( clans[cid].getClanId() );
                    CharacterTable.getInstance().storeNewCharacter( pc );
                    CharacterTable.saveCharStatus( pc );

                }
                clans[0].setHouseId( 100 );
                clans[0].setCastleId( 100 );
                ClanTable.getInstance().updateClan( clans[0] );
                L1Clan getclan = ClanTable.getInstance().getTemplate( clans[0].getClanId() );
                Debug.Assert( getclan != null );
                getclan = ClanTable.getInstance().getTemplate( 0 );
                Debug.Assert( getclan == null );
            }
            {//DropItemTable
                // リストが76個しかなく意味が理解できない
                double dropAmount = DropItemTable.getInstance().getDropAmount( 1 );
                double dropRate = DropItemTable.getInstance().getDropRate( 1 );
            }
            {//DropTable
                int npcid = NpcTable.getInstance().findNpcIdByName( "ゴブリン" );
                int npcid2 = NpcTable.getInstance().findNpcIdByNameWithoutSpace( "グレートダークエレメンタル" );
                L1NpcInstance npc = NpcTable.getInstance().newNpcInstance( npcid );
                L1Inventory inv = new L1Inventory();
                DropTable.getInstance().setDrop( npc, inv );
            }
            {//ExpTable
                int exp1 = ExpTable.getExpByLevel( 2 );
                Debug.Assert( exp1 == 125 );
                int exp2 = ExpTable.getNeedExpNextLevel( 2 );
                Debug.Assert( exp2 == 175 );
                int exp3 = ExpTable.getLevelByExp( 751 );
                Debug.Assert( exp3 == 5 );
                int exp4 = ExpTable.getExpPercentage( 3, 411 );
                double exp5 = ExpTable.getPenaltyRate( 65 );
            }
            {//FurnitureSpawnTable
                int npcid = SqlUtils.toInt( 80124 );
                L1Npc l1npc = NpcTable.getInstance().getTemplate( npcid );
                L1FurnitureInstance furniture = new L1FurnitureInstance( l1npc );
                furniture.setId( IdFactory.getInstance().nextId() );
                furniture.setItemObjId( 111 );
                furniture.setX( 22 );
                furniture.setY( 33 );
                furniture.setMap( 44 );
                FurnitureSpawnTable.getInstance().insertFurniture( furniture );
                FurnitureSpawnTable.getInstance().deleteFurniture( furniture );
            }
            {//HouseTable
                L1House house = HouseTable.getInstance().getHouseTable( 262145 );
                L1House[] houses = HouseTable.getInstance().getHouseTableList();
                String houseName = house.getHouseName();
                house.setHouseName( "テスト" );
                HouseTable.getInstance().updateHouse( house );
                house.setHouseName( houseName );
                HouseTable.getInstance().updateHouse( house );
                int[] houseid = HouseTable.getHouseIdList();
            }
            {//IpTable
                String ip = "123.123.123.123";
                IpTable.getInstance().banIp( ip );
                bool ban = IpTable.getInstance().isBannedIp( ip );
                Debug.Assert( ban == true );
                IpTable.getInstance().liftBanIp( ip );
                ban = IpTable.getInstance().isBannedIp( ip );
                Debug.Assert( ban == false );
            }
            {//LetterTable
                int letterId = IdFactory.getInstance().nextId();
                LetterTable.writeLetter(
                    letterId, 0, "sender", "receiver", "data",
                    1, Encoding.UTF8.GetBytes( "subject" ), Encoding.UTF8.GetBytes( "content" ) );
                LetterTable.deleteLetter( letterId );
            }
            {//LightSpawnTable
                LightSpawnTable.getInstance();
            }
            {//LogEnchantTable
                LogEnchantTable.storeLogEnchant( 10, 20, 30, 40 );
            }
            {//MailTable
                List<byte> datas = new List<byte>();
                datas.AddRange( Encoding.GetEncoding( "SJIS" ).GetBytes( "タイトル" ) );
                datas.Add( 0 );
                datas.Add( 0 );
                datas.AddRange( Encoding.GetEncoding( "SJIS" ).GetBytes( "内容" ) );
                datas.Add( 0 );
                datas.Add( 0 );
                MailTable.getInstance().writeMail( 1, "receiver", pc, datas.ToArray() );

                List<L1Mail> mails = MailTable.getAllMail();
                int mailid = mails[0].getId();
                L1Mail mail = MailTable.getMail( mailid );
                MailTable.getInstance().setReadStatus( mailid );
                MailTable.getInstance().setMailType( mailid, 1 );
            }
            {//PetItemTable
                PetItemTable.getInstance().getTemplate( 40749 );
            }
            {//PetTable
                L1NpcInstance npc1 = NpcTable.getInstance().newNpcInstance( 45034 ); // シェパード
                L1NpcInstance npc2 = NpcTable.getInstance().newNpcInstance( 45043 ); // ウルフ
                PetTable.getInstance().storeNewPet( npc1, 100, 100 );
                PetTable.getInstance().storeNewPet( npc2, 200, 200 );
                PetTable.isNameExists( "ウルフ" );
                L1Pet pet = new L1Pet();
                pet.set_objid( 200 );
                pet.set_npcid( 45043 );
                pet.set_name( "ウルフtest" );
                pet.set_level( 5 );
                pet.set_hp( 100 );
                pet.set_mp( 100 );
                pet.set_exp( 100 );
                pet.set_lawful( 100 );
                pet.set_itemobjid( 200 );
                PetTable.getInstance().storePet( pet );
                PetTable.isNameExists( pet.get_name() );
                PetTable.getInstance().getTemplate( 100 );
                foreach ( L1Pet temp in PetTable.getInstance().getPetTableList() )
                {
                    _log.info( temp.get_name() );
                }
                PetTypeTable.getInstance().get( 45034 );
                PetTable.getInstance().deletePet( 200 );
                PetTable.getInstance().deletePet( 100 );
            }
            {//PolyTable
                L1PolyMorph polyMorth = PolyTable.getInstance().getTemplate( "milkcow" );
                PolyTable.getInstance().getTemplate( polyMorth.getId() );
            }
            {//ResolventTable
                ResolventTable.getInstance().getCrystalCount( 140329 );
            }
            {//ShopTable
                L1Shop shop = ShopTable.getInstance().get( 50118 );
            }
            {//SpawnTable
                L1Spawn spawn = SpawnTable.getInstance().getTemplate( 1 );// カエル
                SpawnTable.getInstance().addNewSpawn( spawn );
                L1Npc l1npc = NpcTable.getInstance().getTemplate( 45034 );   // シェパード
                SpawnTable.storeSpawn( pc, l1npc );
            }
            {//SprTable
                SprTable.getInstance().getAttackSpeed( 0, 0 );
                SprTable.getInstance().getMoveSpeed( 0, 0 );
                SprTable.getInstance().getDirSpellSpeed( 0 );
                SprTable.getInstance().getNodirSpellSpeed( 0 );
            }
            {//TownTable
                foreach ( L1Town town in TownTable.getInstance().getTownTableList() )
                {
                    TownTable.getInstance().getTownTable( town.get_townid() );
                    TownTable.getInstance().isLeader( pc, town.get_townid() );
                    TownTable.getInstance().addSalesMoney( town.get_townid(), 1000 );
                    TownTable.getInstance().updateTaxRate();
                    TownTable.getInstance().updateSalesMoneyYesterday();
                }
            }
            {//TrapTable
                TrapTable.reload();
            }
            {//UBSpawnTable
                UBSpawnTable.getInstance().getPattern( 1, 1 );
            }
            {//UBTable
                UBTable.getInstance().getUbForNpcId( 50037 );
                UBTable.getInstance().getMaxPattern( 1 );
            }
            {//WeaponSkillTable
                WeaponSkillTable.getInstance().getTemplate( 47 );
            }
        }
        private void testCharacterItemTable( L1PcInstance pc )
        {
            L1ItemInstance item = ItemTable.getInstance().createItem( 1 );
            CharacterItemsTable.storeItem( pc.getId(), item );
            // あまり良いテストじゃないけど・・
            item.setItemId( 100 );
            CharacterItemsTable.updateItemId( item );
            item.setCount( 100 );
            CharacterItemsTable.updateItemCount( item );
            item.set_durability( 200 );
            CharacterItemsTable.updateItemDurability( item );
            item.setChargeCount( 100 );
            CharacterItemsTable.updateItemChargeCount( item );
            item.setRemainingTime( 100 );
            CharacterItemsTable.updateItemRemainingTime( item );
            item.setEnchantLevel( 100 );
            CharacterItemsTable.updateItemEnchantLevel( item );
            item.setEquipped( true );
            CharacterItemsTable.updateItemEquipped( item );
            item.setIdentified( true );
            CharacterItemsTable.updateItemIdentified( item );
            item.setLastUsed( DateTime.Now );
            CharacterItemsTable.updateItemDelayEffect( item );
            item.setBless( 100 );
            CharacterItemsTable.updateItemBless( item );
            item.setAttrEnchantKind( 100 );
            CharacterItemsTable.updateItemAttrEnchantKind( item );
            item.setAttrEnchantLevel( 100 );
            CharacterItemsTable.updateItemAttrEnchantLevel( item );

            CharacterItemsTable.getItemCount( pc.getId() );
            CharacterItemsTable.deleteItem( item );
        }

        private void GomiClear()
        {
            List<String> delarr = new List<String>();
            using ( MySqlWrapper wrapper = new MySqlWrapper() )
            {
                MySqlCommand cmd;
                String sqlstr = "select char_name,account_name from characters where account_name like '" + accountName + "%'";
                foreach ( DataRow dr in wrapper.GetDataTable( sqlstr ).Rows )
                {
                    String _char_name = Convert.ToString( dr["char_name"] );
                    String _account_name = Convert.ToString( dr["account_name"] );
                    CharacterTable.getInstance().deleteCharacter( _account_name, _char_name );
                }
                sqlstr = "delete from accounts           where login like '" + accountName + "%'";
                cmd = new MySqlCommand( sqlstr );
                wrapper.ExecNonQuery( cmd );
            }
        }

        private void testItemTable()
        {
            int itemid = ItemTable.getInstance().findItemIdByName( "ランプ" );
            Debug.Assert( itemid != 0, "ItemTable.findItemIdByNameから'ランプ'のアイテムID取得に失敗" );
            itemid = ItemTable.getInstance().findItemIdByNameWithoutSpace( "ランプ" );
            Debug.Assert( itemid != 0, "ItemTable.findItemIdByNameWithoutSpaceから'ランプ'のアイテムID取得に失敗" );

            L1Item item = ItemTable.getInstance().getTemplate( 0 );
            Debug.Assert( item == null, "ItemTable.getTamplate(0)がNULL以外を返したぞ" );
            item = ItemTable.getInstance().getTemplate( 240100 );
            Debug.Assert( item != null, "ItemTable.getTamplate(240100)がNULLを返したぞ" );
            item = ItemTable.getInstance().getTemplate( 240101 );
            Debug.Assert( item == null, "ItemTable.getTamplate(0)がNULL以外を返したぞ" );
            item = ItemTable.getInstance().getTemplate( itemid );
            Debug.Assert( item != null, "ItemTable.getTamplate(0)がNULL以外を返したぞ" );
        }

        private void testAccounts( Account account )
        {
            account.updateLastActive();
            _log.info( account.countCharacters() + "体のキャラクター所持" );
            account.ban();
            DataTable dt = getDataTable( "select * from accounts where login = '" + account.getName() + "'" );
            Debug.Assert( Convert.ToInt32( dt.Rows[0]["banned"] ) == 1, "banに成功してないぞ！" );
            account.setCharacterSlot( 6 );
            dt = getDataTable( "select * from accounts where login = '" + account.getName() + "'" );
            Debug.Assert( Convert.ToInt32( dt.Rows[0]["character_slot"] ) == 6, "character_slotの更新に成功してないぞ！" );
        }

        private void testCharacterTable( L1PcInstance pc )
        {
            bool b;
            b = CharacterTable.doesCharNameExist( char_name );
            Debug.Assert( b == true );
            b = CharacterTable.doesCharNameExist( char_name + "2" );
            Debug.Assert( b == false );
            CharacterTable.getInstance().storeCharacter( pc );
            CharacterTable.getInstance().restoreCharacter( char_name );
            CharacterTable.getInstance().loadCharacter( char_name );
            CharacterTable.updateOnlineStatus( pc );
            CharacterTable.updatePartnerId( pc.getId() );
            CharacterTable.getInstance().restoreInventory( pc );
            L1CharName charName = CharacterTable.getInstance().getL1CharName( "とけび" );
        }

        private DataTable getDataTable( String sqlstr )
        {
            DataTable dt;
            using ( MySqlWrapper wr = new MySqlWrapper() )
            {
                dt = wr.GetDataTable( sqlstr );
            }
            return dt;
        }

        private void benshWorldMap()
        {
            if ( false )
            {
                // Dictionary のアクセスは異常なほど早いようだ
                // 10000件取り出しで16㍉秒
                short[] mapidlist = new short[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 213, 217, 221, 237, 240, 241, 242, 243, 244, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 320, 330, 340, 350, 360, 370, 400, 401, 410, 420, 430, 440, 441, 442, 443, 444, 445, 446, 447, 450, 451, 452, 453, 454, 455, 456, 457, 460, 461, 462, 463, 464, 465, 466, 467, 468, 470, 471, 472, 473, 474, 475, 476, 477, 478, 480, 481, 482, 483, 484, 490, 491, 492, 493, 494, 495, 496, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 511, 512, 513, 514, 515, 516, 521, 522, 523, 524, 530, 531, 532, 533, 534, 535, 536, 541, 542, 543, 550, 551, 552, 553, 554, 555, 556, 557, 558, 600, 601, 602, 603, 604, 605, 606, 607, 608, 610, 611, 612, 666, 701, 777, 778, 779, 780, 781, 782, 783, 784, 997, 998, 1000, 1001, 2000, 2001, 2002, 2003, 2004, 4941, 5001, 5002, 5003, 5004, 5005, 5006, 5007, 5008, 5009, 5010, 5011, 5012, 5013, 5014, 5015, 5016, 5017, 5018, 5019, 5020, 5021, 5022, 5023, 5024, 5025, 5026, 5027, 5028, 5029, 5030, 5031, 5032, 5033, 5034, 5035, 5036, 5037, 5038, 5039, 5040, 5041, 5042, 5043, 5044, 5045, 5046, 5047, 5048, 5049, 5050, 5051, 5052, 5053, 5054, 5055, 5056, 5057, 5058, 5059, 5060, 5061, 5062, 5063, 5064, 5065, 5066, 5067, 5068, 5069, 5070, 5071, 5072, 5073, 5074, 5075, 5076, 5077, 5078, 5079, 5080, 5081, 5082, 5083, 5084, 5085, 5086, 5087, 5088, 5089, 5090, 5091, 5092, 5093, 5094, 5095, 5096, 5097, 5098, 5099, 5100, 5101, 5102, 5103, 5104, 5105, 5106, 5107, 5108, 5109, 5110, 5111, 5112, 5113, 5114, 5115, 5116, 5117, 5118, 5119, 5120, 5121, 5122, 5123, 5124, 5125, 5131, 5132, 5133, 5134, 5140, 5701, 5801, 5802, 5803, 5804, 5805, 7000, 7001, 7002, 7003, 7004, 7005, 7006, 7007, 7008, 7009, 7010, 7011, 7051, 7052, 7053, 7054, 7055, 8011, 8012, 8013, 8014, 8015, 16384, 16896, 17408, 17920, 18432, 18944, 19456, 19968, 20480, 20992, 21504, 22016, 22528, 23040, 23552, 24064, 24576, 25088 };
                Random random = new Random();
                int count = 100000;
                PerformanceTimer check = new PerformanceTimer();
                check.reset();
                for ( int i = 0; i < count; i++ )
                {
                    L1WorldMap.getInstance().getMap( (short)random.Next( mapidlist.Length ) );
                    if ( ( i % 10000 ) == 0 && i != 0 )
                    {
                        _log.info( i + "件目\t" + check.get() + "㍉秒" );
                    }
                }
                _log.info( count + "件目\t" + check.get() + "㍉秒" );
            }
        }

        private Account initAccount()
        {
            Account account = new Account();
            if ( account.load( accountName ) == false )
            {
                account.create( accountName, password, ip, host );
            }

            // Accountの追加性能チェック兼テストアカウント作成
            if ( false )
            {
                //           ノートPC                        デスクトップ core2 3GHz
                // １つ目
                // 1000件目   20750㍉秒  0.020750000㍉秒/件
                // ２つ目
                // 1000件目     953㍉秒  0.000953000㍉秒/件   343㍉秒  0.000343000㍉秒/件
                // 2000件目    1703㍉秒  0.000851500㍉秒/件   672㍉秒  0.000336000㍉秒/件
                // 3000件目    2594㍉秒  0.000864667㍉秒/件  1031㍉秒  0.000343667㍉秒/件
                // 4000件目    3609㍉秒  0.00090225㍉秒/件   1422㍉秒  0.000355500㍉秒/件
                // 5000件目    4640㍉秒  0.000928000㍉秒/件  1843㍉秒  0.000368600㍉秒/件
                // 6000件目    5812㍉秒  0.000968667㍉秒/件  2297㍉秒  0.000382833㍉秒/件
                // 7000件目    7109㍉秒  0.001015571㍉秒/件  2765㍉秒  0.000395000㍉秒/件
                // 8000件目    8609㍉秒  0.001076125㍉秒/件  3281㍉秒  0.000410125㍉秒/件
                // 9000件目   10344㍉秒  0.001149333㍉秒/件  3812㍉秒  0.000423556㍉秒/件
                // 10000件目  12219㍉秒  0.001221900㍉秒/件  4375㍉秒  0.000437500㍉秒/件
                // ３つ目
                // 1000件目     609㍉秒  0.000609000㍉秒/件   281㍉秒  0.000281000㍉秒/件
                // 2000件目    1219㍉秒  0.000609500㍉秒/件   547㍉秒  0.000273500㍉秒/件
                // 3000件目    1828㍉秒  0.000609333㍉秒/件   844㍉秒  0.000281333㍉秒/件
                // 4000件目    2453㍉秒  0.000613250㍉秒/件  1125㍉秒  0.000281250㍉秒/件
                // 5000件目    3109㍉秒  0.000621800㍉秒/件  1406㍉秒  0.000281200㍉秒/件
                // 6000件目    3734㍉秒  0.000622333㍉秒/件  1687㍉秒  0.000281167㍉秒/件
                // 7000件目    4359㍉秒  0.000622714㍉秒/件  1969㍉秒  0.000281286㍉秒/件
                // 8000件目    5000㍉秒  0.000625000㍉秒/件  2250㍉秒  0.000281250㍉秒/件
                // 9000件目    5640㍉秒  0.000626667㍉秒/件  2531㍉秒  0.000281222㍉秒/件
                // 10000件目   6297㍉秒  0.000629700㍉秒/件  2812㍉秒  0.000281200㍉秒/件

                int count = 1000;
                String _password = "password";
                String _ip = ip;
                String _host = host;
                DateTime _lastActive = DateTime.Now;
                String[] namearr = new String[count];
                PerformanceTimer check = new PerformanceTimer();
                for ( int i = 0; i < count; i++ )
                {
                    namearr[i] = accountName + i;
                }
                // 一つ目
                if ( false )
                {
                    {
                        using ( MySqlWrapper wrapper = new MySqlWrapper() )
                        {
                            String sqlstr = "DELETE FROM accounts where login like 'dummy%'";
                            MySqlCommand cmd = new MySqlCommand( sqlstr );
                            wrapper.ExecNonQuery( cmd );
                        }
                    }
                    check.reset();
                    for ( int i = 0; i < count; i++ )
                    {
                        String sqlstr = "SELECT * FROM accounts";
                        MySqlWrapper wrapper = new MySqlWrapper();
                        MySqlConnection con = wrapper.getConnection();
                        MySqlDataAdapter da = new MySqlDataAdapter( sqlstr, con );
                        da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                        DataTable dt = new DataTable();
                        da.Fill( dt );
                        DataRow dr = dt.NewRow();
                        dr["login"] = namearr[i];
                        dr["password"] = _password;
                        dr["lastactive"] = _lastActive;
                        dr["access_level"] = 0;
                        dr["ip"] = ip;
                        dr["host"] = host;
                        dr["banned"] = false;
                        dr["character_slot"] = 0;
                        dt.Rows.Add( dr );
                        MySqlCommandBuilder cb = new MySqlCommandBuilder( da );
                        da.Update( dt );
                        con.Close();

                        if ( ( i % 1000 ) == 0 && i != 0 )
                        {
                            _log.info( i + "件目\t" + check.get() + "㍉秒" );
                        }
                    }
                    _log.info( count + "件目\t" + check.get() + "㍉秒" );

                    {
                        using ( MySqlWrapper wrapper = new MySqlWrapper() )
                        {
                            String sqlstr = "DELETE FROM accounts where login like 'dummy%'";
                            MySqlCommand cmd = new MySqlCommand( sqlstr );
                            wrapper.ExecNonQuery( cmd );
                        }
                    }
                }
                // ２つ目
                if ( false )
                {
                    check.reset();
                    {
                        String sqlstr = "SELECT * FROM accounts";
                        MySqlWrapper wrapper = new MySqlWrapper();
                        MySqlConnection con = wrapper.getConnection();
                        MySqlDataAdapter da = new MySqlDataAdapter( sqlstr, con );
                        da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                        DataTable dt = new DataTable();
                        da.Fill( dt );
                        for ( int i = 0; i < count; i++ )
                        {
                            dt.Clear();
                            DataRow dr = dt.NewRow();
                            dr["login"] = namearr[i];
                            dr["password"] = _password;
                            dr["lastactive"] = _lastActive;
                            dr["access_level"] = 0;
                            dr["ip"] = ip;
                            dr["host"] = host;
                            dr["banned"] = false;
                            dr["character_slot"] = 0;
                            dt.Rows.Add( dr );
                            MySqlCommandBuilder cb = new MySqlCommandBuilder( da );
                            da.Update( dt );
                            con.Close();

                            if ( ( i % 1000 ) == 0 && i != 0 )
                            {
                                _log.info( i + "件目\t" + check.get() + "㍉秒" );
                            }
                        }
                    }
                    _log.info( count + "件目\t" + check.get() + "㍉秒" );
                    {
                        using ( MySqlWrapper wrapper = new MySqlWrapper() )
                        {
                            String sqlstr = "DELETE FROM accounts where login like 'dummy%'";
                            MySqlCommand cmd = new MySqlCommand( sqlstr );
                            wrapper.ExecNonQuery( cmd );
                        }
                    }
                }
                // ３つ目
                if ( true )
                {
                    check.reset();
                    {
                        String sqlstr = @"INSERT INTO accounts SET
                                login          = ?1,
                                password       = ?2,
                                lastactive     = ?3,
                                access_level   = ?4,
                                ip             = ?5,
                                host           = ?6,
                                banned         = ?7,
                                character_slot = ?8";
                        for ( int i = 0; i < count; i++ )
                        {
                            using ( MySqlWrapper wrapper = new MySqlWrapper() )
                            {
                                MySqlCommand cmdins = new MySqlCommand( sqlstr );
                                cmdins.Parameters.Add( new MySqlParameter( "?1", namearr[i] ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?2", _password ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?3", _lastActive ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?4", (Object)0 ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?5", ip ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?6", host ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?7", false ) );
                                cmdins.Parameters.Add( new MySqlParameter( "?8", (Object)0 ) );
                                wrapper.ExecNonQuery( cmdins );
                                if ( ( i % 1000 ) == 0 && i != 0 )
                                {
                                    _log.info( i + "件目\t" + check.get() + "㍉秒" );
                                }
                            }
                        }
                    }
                    _log.info( count + "件目\t" + check.get() + "㍉秒" );
                }
            }
            return account;
        }

        private void initPcInstance( L1PcInstance pc )
        {
            int[] MALE_LIST = new int[] { 0, 61, 138, 734, 2786, 6658, 6671 };
            int[] FEMALE_LIST = new int[] { 1, 48, 37, 1186, 2796, 6661, 6650 };
            int[] LOCX_LIST = new int[] { 32734, 32734, 32734, 32734, 32734, 32734, 32734 };
            int[] LOCY_LIST = new int[] { 32798, 32798, 32798, 32798, 32798, 32798, 32798 };
            short[] MAPID_LIST = new short[] { 8013, 8013, 8013, 8013, 8013, 8013, 8013 };
            // キャラクターの初期パラメータ
            //        君　戦　エ　ウ　ダ　ド　イ
            //   STR  13, 16, 11,  8, 12, 13, 11 
            //   DEX  10, 12, 12,  7, 15, 11, 10 
            //   CON  10, 14, 12, 12,  8, 14, 12 
            //   WIS  11,  9, 12, 12, 10, 12, 12 
            //   CHA  13, 12,  9,  8,  9,  8,  8 
            //   INT  10,  8, 12, 12, 11, 11, 12 
            // AMOUNT  8,  4,  7, 16, 10,  6, 10 
            pc.setName( char_name );
            pc.setType( 3 ); // 0:君　1:戦　2:エ　3:ウ　4:ダ　5:ド　6:イ
            pc.set_sex( 0 );
            pc.addBaseStr( 8 );
            pc.addBaseDex( 7 );
            pc.addBaseCon( 12 + 4 );
            pc.addBaseWis( 12 + 6 );
            pc.addBaseCha( 8 );
            pc.addBaseInt( 12 + 6 );
            pc.setId( IdFactory.getInstance().nextId() );
            if ( pc.get_sex() == 0 )
            {
                pc.setClassId( MALE_LIST[pc.getType()] );
            }
            else
            {
                pc.setClassId( FEMALE_LIST[pc.getType()] );
            }
            pc.setX( LOCX_LIST[pc.getType()] );
            pc.setY( LOCY_LIST[pc.getType()] );
            pc.setMap( MAPID_LIST[pc.getType()] );
            pc.setHeading( 0 );
            pc.setLawful( 0 );

            int initHp = CalcInitHpMp.calcInitHp( pc );
            int initMp = CalcInitHpMp.calcInitMp( pc );
            pc.addBaseMaxHp( (short)initHp );
            pc.setCurrentHp( (short)initHp );
            pc.addBaseMaxMp( (short)initMp );
            pc.setCurrentMp( (short)initMp );
            pc.resetBaseAc();
            pc.setTitle( "" );
            pc.setClanid( 0 );
            pc.setClanRank( 0 );
            pc.set_food( 40 );
            pc.setAccessLevel( (short)0 );
            pc.setGm( false );
            pc.setMonitor( false );
            pc.setGmInvis( false );
            pc.setExp( 0 );
            pc.setHighLevel( 0 );
            pc.setStatus( 0 );
            pc.setAccessLevel( (short)0 );
            pc.setClanname( "" );
            pc.setBonusStats( 0 );
            pc.setElixirStats( 0 );
            pc.resetBaseMr();
            pc.setElfAttr( 0 );
            pc.set_PKcount( 0 );
            pc.setPkCountForElf( 0 );
            pc.setExpRes( 0 );
            pc.setPartnerId( 0 );
            pc.setOnlineStatus( 0 );
            pc.setHomeTownId( 0 );
            pc.setContribution( 0 );
            pc.setBanned( false );
            pc.setKarma( 0 );
            if ( pc.isWizard() )
            { // WIZ
                int object_id = pc.getId();
                L1Skills l1skills = SkillsTable.getInstance().getTemplate( 4 ); // EB
                String skill_name = l1skills.getName();
                int skill_id = l1skills.getSkillId();
                SkillsTable.getInstance().spellMastery( object_id, skill_id, skill_name, 0, 0 ); // DBに登録
                SkillsTable.getInstance().spellMastery( object_id, 1, "ヒール", 0, 0 ); // DBに登録
                SkillsTable.getInstance().spellLost( object_id, 1 );
            }
            Beginner.getInstance().GiveItem( pc );
            pc.setAccountName( accountName );
            CharacterTable.getInstance().storeNewCharacter( pc );
            CharacterTable.saveCharStatus( pc );
            pc.refresh();
        }
    }
#endif
}
